package org.java.auth.service;

import org.java.auth.vo.SecurityUserDetails;
import org.java.user.api.UserCenter;
import org.java.user.api.damain.Role;
import org.java.user.api.damain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class RemoteUserDetailsService implements UserDetailsService {
    // 调用userCenter对象里面的方法，实际上会发送HTTP请求到user-center里面，然后访问其中的控制器。
    @Autowired
    private UserCenter userCenter;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user  = userCenter.loadUserByName(username);
        System.out.println(user+"--------------->");
        if (user == null){
            throw new UsernameNotFoundException("无法找到" + username + "对应的用户数据");
        }
        // 用户具有的角色
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<Role> roles = user.getRoles();
        roles.forEach(role -> {
            // ROLE_ 是固定的、必须的！Spring Security规定的！
            SimpleGrantedAuthority authority
                    = new SimpleGrantedAuthority("ROLE_" + role.getRoleKey());
            authorities.add(authority);
        });

        return new SecurityUserDetails(user, authorities);
    }
}
